package com.person.mengshuai.mytestdemo.satoken;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.person.mengshuai.mytestdemo.entity.BRole;
import com.person.mengshuai.mytestdemo.service.BMenuService;
import com.person.mengshuai.mytestdemo.service.BRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 */
@Component
@RequiredArgsConstructor
public class StpInterfaceImpl implements StpInterface {
    @Autowired
    private BMenuService menuService;

    @Autowired
    private BRoleService roleService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        SaSession session = StpUtil.getSessionByLoginId(loginId);
        return session.get(SaTokenConstant.PERMISSION_LIST, () -> {
            List<BRole> bRoles = roleService.getBRoleListByUserId(loginId.toString());
            if (CollectionUtils.isEmpty(bRoles)) {
                return null;
            }
            List<Integer> roleIds = bRoles.stream().map(BRole::getId).collect(Collectors.toList());
            return menuService.getPermissionNamesByRoleIds(roleIds);
        });
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        SaSession session = StpUtil.getSessionByLoginId(loginId);
        return session.get(SaTokenConstant.ROLE_LIST, () -> roleService.getRoleNamesByUserId(loginId.toString()));
    }
}
